package chen.web.util;

/**
 * 对数字加密和解密
 *
 */
public class NumberEncryption {

    private static final byte[] ENCODE_TABLE = {
    	'J', 'I', 'H', 'G', 'F', 'A', 'M', 'L', 'K', 'W', 'V', '3', 'y', 
    	'Z', 'Y', 'X', '2', 'U', 'C', 'B', 'i', 'h', 'g', 'f', 'e', 'x', 
        'u', 't', 's', 'r', 'n', 'R', 'Q', 'P', 'O', 'N', 'q', 'p', 'o',
        '5', '4', '1', '0', 'c', 'b', 'a', '9', '8', '7', '6', 'E', 'D', 
        'z', 'v', 'm', 'l', 'k', 'j', 'd', 'T', 'S', 'w'
    };
    
    private static final byte[] DECODE_TABLE = {
    	-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,42,41,16,11,40,39,49,48,47,46,-1,-1,-1,-1,-1,-1,-1,5,19,18,51,50,4,3,2,1,0,8,7,6,35,34,33,32,31,60,59,17,10,9,15,14,13,-1,-1,-1,-1,-1,-1,45,44,43,58,24,23,22,21,20,57,56,55,54,30,38,37,36,29,28,27,26,53,61,25,12,52,-1,-1,-1,-1,-1
    };
	
	public static String encrypt(int i){
		char buf[] = new char[7];
		boolean negative = (i < 0);
		int charPos = 6;
		
		if (!negative) {
		    i = -i;
		}
		
		while (i <= -62) {
		    buf[charPos--] = (char)ENCODE_TABLE[-(i % 62)];
		    i = i / 62;
		}
		buf[charPos] = (char)ENCODE_TABLE[-i];
		if (negative) {
		    buf[--charPos] = '-';
		}
		return new String(buf, charPos, (7 - charPos));
	}
	
	public static int decrypt(String str){
		int result = 0;
		int m = str.length();
		boolean negative = false;
		if(str.charAt(0) == '-'){
			negative = true;
		}
		int j = negative ? 1 : 0;
		int n = 0;
		for(int i=m-1; i>=j; i--){
			char ch = str.charAt(i);
			result = result + DECODE_TABLE[ch] * pow(62, n);
			n++;
		}
		
		if(negative){
			result = -result;
		}
		return result;
	}
	
	private static int pow(int i, int n){
		if(n==0){
			return 1;
		}
		if(n==1){
			return i;
		}
		int result = i;
		for (int j = 1 ; j < n ; j++)
		{
			result = result*i;
		} 
		return result;
	}
	
}
